/**
 * @author: giscafer ,https://github.com/giscafer
 * @date: 2018-12-3 
 * @description: 
 */


// index page

var mongoose = require('mongoose')
var Products = mongoose.model('Products')
var Feedback = mongoose.model('Feedback')

/*处理时间*/
var Moment = require('moment')
var request = require('request');

function getUserInfo(req) {
  var isVisitor = false
  if (req.session.user && req.session.user.status == '-1') {
    isVisitor = true
  }
  var isSuper = ''
  if (req.session.user && req.session.user.status === '2') {
    isSuper = '超级管理员'
  } else if (req.session.user && req.session.user.status == '-1') {
    // 访客
    isSuper = false
  } else if (req.session.user && req.session.user.status === '1') {
    isSuper = '普通管理员'
  }

  return {
    isVisitor,
    isSuper,
    user: req.session.user || {}
  }
}

exports.github = function (req, res) {
  const url = req.query.url;
  const token = req.query.token;
  let options = {
    headers: {
      'User-Agent': 'Mozilla/5.0 (Windows NT 10; Win64; x64; rv:60.0) Gecko/20100101 Firefox/60.0',
      'method': 'GET',
    }
  }
  console.log(url)
  if (url.indexOf('api.github.com') !== -1) {
    options.headers.Authorization = 'token ' + token;
  }
  request(url, options, function (error, response, body) {
    if (!error && response.statusCode == 200) {
      res.send(body);
    }
  })
}

// 首页
exports.index = function (req, res) {
  const { user = {}, isSuper, isVisitor } = getUserInfo(req)
  res.render('website/index/index', { isVisitor, username: user.username, isSuper: isSuper })
}
exports.has_saled = function (req, res) {
  const { user = {}, isSuper, isVisitor } = getUserInfo(req)
  res.render('website/index/has_saled', { isVisitor, username: user.username, isSuper: isSuper })
}
exports.factory = function (req, res) {
  const { user = {}, isSuper, isVisitor } = getUserInfo(req)
  res.render('website/index/factory', { isVisitor, username: user.username, isSuper: isSuper })
}
exports.promote = function (req, res) {
  const { user = {}, isSuper, isVisitor } = getUserInfo(req)
  res.render('website/index/promote', { isVisitor, username: user.username, isSuper: isSuper })
}
exports.specialBenifit = function (req, res) {
  const { user = {}, isSuper, isVisitor } = getUserInfo(req)
  res.render('website/index/special-benifit', { isVisitor, username: user.username, isSuper: isSuper })
}
exports.fangtuan = function (req, res) {
  const { user = {}, isSuper, isVisitor } = getUserInfo(req)
  res.render('website/index/fangtuan', { isVisitor, username: user.username, isSuper: isSuper })
}

// 联系我们
exports.contact_us = function (req, res) {
  const { user = {}, isSuper, isVisitor } = getUserInfo(req)
  res.render('website/contact_us/contact_us', { isVisitor, username: user.username, isSuper: isSuper })
}

// 首页退出登录按钮
exports.logout_by_home = function (req, res) {
  req.session.user = null
  res.redirect('/index')
}

// 首页获取6条产品
exports.get_products = function (req, res) {
  // 获取产品处理逻辑
  Products.find({ category: '0' }).sort('-_id').limit(6).exec(function (err, datas) {
    if (err) {
      console.log('获取数据失败')
      var data = {
        status: 'failed'
      }
      res.json(data)
    } else {
      var data = {
        status: 'success',
        datas: datas
      }
      res.json(data)
    }
  })
}

// 获取有效的产品
exports.get_products_by_status = function (req, res) {
  // 获取产品处理逻辑
  var curr = req.body.curr
  var status = req.body.status
  var category = req.body.category
  var keyword = req.body.keyword
  var pageSize = req.body.pageSize || 12
  pageSize = +pageSize
  let { isSuper, isVisitor } = getUserInfo(req)
  if (isSuper) {
    isVisitor = 2
  } else if (isVisitor) {
    isVisitor = 1
  }
  if (!status && status != 0) {
    status = 0
  }
  // 关键字搜索
  var _filter = {
    $or: [  // 多字段同时匹配
      { title: { $regex: keyword } },
      // { productNo: { $regex: keyword, $options: '$i' } }
    ]
  }
  var query = Products.find({})
  var conditions = {}
  if (status !== '') {
    query.where('status', status)
    conditions['status'] = status
  }
  if (category) {
    query.where('category', category)
    conditions['category'] = category
  }
  if (keyword) {
    /*     query.where('title', new RegExp(keyword, 'g'));
        conditions['title'] = { $regex: keyword, $options: '$g' } */
    query.or([{ title: new RegExp(keyword, 'g') }, { productNo: new RegExp(keyword, 'g') }]);
    conditions['$or'] = [{ title: { $regex: keyword, $options: '$g' } }, { productNo: { $regex: keyword, $options: '$g' } }]
  }
  // 每页大小
  query.skip((curr - 1) * pageSize)
  query.limit(pageSize)
  // 按照id添加的顺序倒序排列
  query.sort({ 'order': -1 })
  // 计算分页数据
  query.exec(function (err, rs) {
    if (err) {
      res.send(err)
    } else {
      // 计算数据总数
      Products.find(conditions, function (err, result) {
        pages = Math.ceil(result.length / pageSize)
        jsonArray = { data: rs, pages: pages, total: result.length, isVisitor }
        res.json(jsonArray)
      })
    }
  })
}

// 根据类别号分类获取产品
exports.get_products_by_Category = function (req, res) {
  // 获取产品处理逻辑
  var curr = req.body.curr
  var category = req.body.category
  // 每页大小为10
  var query = Products.find({ category: category })
  query.skip((curr - 1) * 10)
  query.limit(10)
  // 按照id添加的顺序倒序排列
  query.sort({ '_id': -1 })
  // 计算分页数据
  query.exec(function (err, rs) {
    if (err) {
      res.send(err)
    } else {
      // 计算数据总数
      Products.find({}, function (err, result) {
        if (result.length % 10 > 0) {
          pages = result.length / 10 + 1
        } else {
          pages = result.length / 10
        }
        jsonArray = { data: rs, pages: pages }
        res.json(jsonArray)
      })
    }
  })
}

// 跳转到公司动态详情页面
exports.get_products_detail = function (req, res) {
  res.render('website/products/company_dynamic_detail')
}
// 获取公司动态详情
exports.post_products_detail = function (req, res) {
  var id = req.params.id
  Products.findOne({ _id: id }, function (err, data) {
    if (err) {
      res.json({ 'status': 'failed' })
    } else {
      res.json({ 'status': 'success', 'data': data })
    }
  })
}

// 跳转媒体报道详情页面
exports.get_media_report_detail = function (req, res) {
  res.render('website/products/media_report_detail')
}
// 获取媒体报道详情
exports.post_media_report_detail = function (req, res) {
  var id = req.params.id
  Products.findOne({ _id: id }, function (err, data) {
    if (err) {
      res.json({ 'status': 'failed' })
    } else {
      res.json({ 'status': 'success', 'data': data })
    }
  })
}

// 跳转活动报道详情页面
exports.get_products_details = function (req, res) {
  const { user = {}, isSuper, isVisitor } = getUserInfo(req)
  res.render('website/products/products_details', { isVisitor, username: user.username, isSuper: isSuper })
}
// 获取活动报道详情
exports.post_products_details = function (req, res) {
  var id = req.params.id
  let { isSuper, isVisitor } = getUserInfo(req)
  if (isSuper) {
    isVisitor = 2
  } else if (isVisitor) {
    isVisitor = 1
  }
  Products.findOne({ _id: id }, function (err, data) {
    if (err) {
      res.json({ 'status': 'failed', isVisitor })
    } else {
      res.json({ 'status': 'success', 'data': data, isVisitor })
    }
  })
}

// 联系我们页面用户反馈
// 添加用户反馈
exports.post_feedback = function (req, res) {
  var name = req.body.name
  var email = req.body.email
  var phone = req.body.phone
  var message = req.body.message
  var time = Moment().format('YYYY-MM-DD HH:mm')

  var data = new Feedback(
    {
      name: name,
      email: email,
      phone: phone,
      message: message,
      time: time,
      status: '0'
    }
  )
  data.save(function (err) {
    if (err) {
      res.json({ 'status': 'error' })
    } else {
      res.json({ 'status': 'success' })
    }
  })
}

